package hn.cch.security.util;


import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class VerifyCodeUtil {


    /**
     * 获取验证码
     *
     * @param width
     * @param height
     * @return
     */

    public static Map<String, Object> getVerifyCode(int width, int height) {

        //随机类
        Random random = new Random();


        //创建图片
        BufferedImage image = new BufferedImage(width, height, BufferedImage
                .TYPE_INT_RGB);
        //获取图形
        Graphics graphics = image.getGraphics();

        //设置背景色
        graphics.setColor(new Color(255, 255, 255));
        graphics.fillRect(0, 0, width, height);

        //设置前景色
        graphics.setColor(new Color(0, 0, 0));
        //设置字体
        graphics.setFont(new Font("Times New Roman", Font.PLAIN, 18));


        //验证码字符个数
        int codeLength = 4;
        //验证码
        StringBuffer code = new StringBuffer();
        //随机生成验证码
        for (int i = 0; i < codeLength; ++i) {
            //随机生成数字
            code.append(random.nextInt(10));
        }
        graphics.drawString(code.toString(), 19, 16);

        // 干扰线
        for (int i = 0; i < codeLength; i++) {
            graphics.setColor(new Color(random.nextInt(256), random.nextInt(256),
                    random.nextInt(256)));
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            int xl = random.nextInt(18);
            int yl = random.nextInt(18);
            graphics.drawLine(x, y, x + xl, y + yl);
        }
        // 释放图形
        graphics.dispose();
        Map<String, Object> map = new HashMap<>();
        map.put("image", image);
        map.put("code", code.toString());
        return map;
    }
}
